package com.wenwu.controller.competence;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wenwu.common.bean.Role;
import com.wenwu.common.bean.RoleResources;
import com.wenwu.common.page.PageUtils;
import com.wenwu.common.page.PaginationVO;
import com.wenwu.common.utils.JsonUtils;
import com.wenwu.service.RoleService;

/**
 * @project ATHome-Manager
 * @class RoleController.java
 * @author zhujiagui E-mail:<zhujiagui@zkingsoft.com>
 * @date 2015年3月3日 下午5:47:24
 * @description 角色管理模块
 */
@Controller(value = "RoleController")
@RequestMapping(value = "/role")
public class RoleController {
	@Autowired
	private RoleService roleService;
	Logger log = Logger.getLogger(this.getClass());
	private int result = 0;
	// 用来创建json数据
	private JsonGenerator jsonGenerator = null;

	// 进入页面
	@RequestMapping(value = "/mgr/init")
	public String initPage() {
		log.info("进入角色模块页面...");
		return "role/rolelist";
	}

	@RequestMapping(value = "/mgr/roleform")
	public String functionform() {
		return "role/roleform";
	}

	// 进入角色分配资源页面
	@RequestMapping(value = "/mgr/roleresource")
	public String roleresource() {
		return "role/roleresource";
	}

	// 查询function数据
	@RequestMapping(value = "/mgr/showList")
	public void showList(Model model, HttpServletRequest request,
			HttpServletResponse response, Role role) throws Exception {
		log.info("查询角列表...");
		PaginationVO pageVo = PageUtils.getPaginationInfo(request);
		try {
			int totalRecord = roleService.selectTotalRecord(role, pageVo);// 查询符合条件的个数
			List<Role> list = roleService.selectList(role, pageVo);// 查询符合条件的数据
			pageVo.setList(list);// 将数据设置到PaginationVO对象中
			pageVo.setTotalRecord(totalRecord);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(pageVo);// 将PaginationVO对象以json格式写回页面
		} catch (Exception e) {// 异常处理
			log.info(e.getMessage());
			model.addAttribute("errorMsg", "系统异常，请稍后重试!");
		}
	}

	/**
	 * 增加
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/addRole", method = { RequestMethod.POST })
	public void addRole(Role role, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			if (role.getRoleId() == null) {
				java.text.DateFormat format = new java.text.SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				role.setAddTime(format.format(new Date()));
				roleService.addRole(role);
				jsonGenerator.writeObject("添加成功");
			} else {
				result = roleService.updateRole(role);
				jsonGenerator.writeObject("修改成功");
			}
		} catch (Exception e) {
			jsonGenerator.writeObject("保存失败," + e.getMessage());
		}
	}

	/**
	 * 查询修改信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/showUpdate")
	public void showUpdate(HttpServletResponse response,
			@RequestParam(required = false, value = "roleId") Integer roleId)
			throws Exception {
		if (roleId != null) {
			Role role = roleService.selectByKey(roleId);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(role);
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param response
	 * @param userId
	 * @throws Exception
	 */
	@RequestMapping(value = "/mgr/deleteRole")
	public void deleteRole(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "key") String key)
			throws Exception {
		log.info("主键：" + key);
		if (key != null) {
			List<String> keys = new ArrayList<String>();
			String[] objs = key.split(",");
			for (String k : objs) {
				keys.add(k);
			}
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			try {
				result = roleService.deleteRoleByKey(keys);
				jsonGenerator.writeObject("成功删除" + result + "条数据");
			} catch (Exception e) {
				jsonGenerator.writeObject("删除数据失败");
			} 
		}
	}

	/**
	 * 分配角色资源
	 * 
	 * @param response
	 * @param key
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/mgr/addAllotResource")
	public void addAllotResource(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "datas") String datas,
			@RequestParam(required = false, value = "roleid") Integer roleid)
			throws Exception {
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		try {
			List<RoleResources> list = null;
			if (!StringUtils.isEmpty(datas)) {
				JSONArray array = null;// 将json数组转为对象
				array = JSONArray.fromObject(datas);
				list = (List<RoleResources>) JSONArray.toCollection(array,
						RoleResources.class);
			}
			if (list != null) {
				int result = roleService.saveBatchByRoleId(list, roleid);
				if (result > 0) {
					jsonGenerator.writeObject("true");// 保存成功
				} else {
					jsonGenerator.writeObject("false");
				}
			}
		} catch (Exception e) {
			log.info(e.getMessage());
			jsonGenerator.writeObject("系统异常");
		} 
	}

	/**
	 * 显示角色已分配资源
	 */
	@RequestMapping(value = "/mgr/showRoleResource")
	public void showRoleResource(HttpServletResponse response,
			@RequestParam(required = false, value = "roleId") Integer roleId)
			throws Exception {
		if (roleId != null) {
			// 获取选中角色已分配的资源
			List<RoleResources> list = roleService.selectCurrentList(roleId);
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			jsonGenerator.writeObject(list);
		}
	}
}
